package org.yh.security;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.BeanIds;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.CorsConfigurationSource;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.yh.Handler.CustomAccessDeniedHandler;
import org.yh.filter.JwtAuthenticationFilter;
import org.yh.filter.JwtLoginFilter;

import javax.sql.DataSource;

/**
 * @Author: yh
 * @Description:
 * @Date: Created in 15:53 2018/12/5
 * @Modified By:
 */
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    //@Autowired
    //private DataSource dataSource;

    @Autowired
    private CustomAccessDeniedHandler customAccessDeniedHandler;

    /**
     * 配置认证信息
     *
     * @param auth
     * @throws Exception
     */
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(customUserService()).passwordEncoder(passwordEncoder());
    }


    /**
     * 设置拦截忽略文件夹，可以对静态资源放行
     *
     * @param web
     * @throws Exception
     */
    @Override
    public void configure(WebSecurity web) throws Exception {
        // 设置拦截忽略文件夹，可以对静态资源放行
        web.ignoring().antMatchers("/view/*.html", "/css/**", "/js/**", "/images/**");
    }

    /**
     * 配置拦截请求资源
     *
     * @param http
     * @throws Exception
     */
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                //关闭csrf跨域
                .cors().and()
                .csrf().disable()
                // .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).and()
                .authorizeRequests()
                .antMatchers("/captcha.jpg", "/userLogin", "/register").permitAll()
                // 任何尚未匹配的URL只需要对用户进行身份验证
                .anyRequest().authenticated()
                .and()
                .formLogin().loginPage("/login")
                //设置默认登录成功页面
                .defaultSuccessUrl("/")
                .failureUrl("/login/error")
                //设置默认登录参数
                .usernameParameter("username").passwordParameter("password").permitAll()
                .and()
                .addFilter(new JwtLoginFilter(authenticationManager()))
                .addFilter(new JwtAuthenticationFilter(authenticationManager()))
                .logout().logoutUrl("/logout").permitAll()
                //权限拒绝方法
                .and().exceptionHandling()
                // .accessDeniedPage("/403");
                .accessDeniedHandler(customAccessDeniedHandler);
        //两种认证方式 1.httpBasic 2.formLogin表单认证
        //设置rememberMe功能 ， 时间为24h
        // http.rememberMe().tokenRepository(persistentTokenRepository()).tokenValiditySeconds(3600*24).userDetailsService(customUserService());
    }

    //@Bean
    //public PersistentTokenRepository persistentTokenRepository() {
    //    JdbcTokenRepositoryImpl tokenRepository = new JdbcTokenRepositoryImpl();
    //    tokenRepository.setDataSource(dataSource);
    //    // 如果token表不存在，使用下面语句可以初始化该表；若存在，会报错。这个参数到第二次启动时必须注释掉，因为已经创建了一张表
    //    //tokenRepository.setCreateTableOnStartup(true);
    //    return tokenRepository;
    //}

    @Bean
    public BCryptPasswordEncoder passwordEncoder() {
        //密码加密 强度为4
        return new BCryptPasswordEncoder(4);
    }

    /**
     * 自定义用户权限service
     *
     * @return
     */
    @Bean
    UserDetailsService customUserService() {
        return new SecurityUserService();
    }

    /**
     * AuthenticationManager
     *
     * @return
     * @throws Exception
     */
    @Bean(name = BeanIds.AUTHENTICATION_MANAGER)
    @Override
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }

    @Bean
    CorsConfigurationSource corsConfigurationSource() {
        final UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", new CorsConfiguration().applyPermitDefaultValues());
        return source;
    }

}


